from rest_framework.test import APITestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from .models import Scene, Trigger, Action


User = get_user_model()


class SceneAPITest(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='testuser', password='pass')
        self.client.force_authenticate(self.user)

    def test_create_and_list_scenes(self):
        url = reverse('scene-list')
        resp = self.client.post(url, {
            'name': '回家模式',
            'owner': self.user.id,
            'priority': 3,
            'enabled': True
        }, format='json')
        self.assertEqual(resp.status_code, 201)
        list_resp = self.client.get(url, {'page': 1, 'page_size': 10})
        self.assertEqual(list_resp.status_code, 200)
        self.assertIn('results', list_resp.data)

    def test_add_and_remove_action(self):
        scene = Scene.objects.create(name='模式A', owner=self.user)
        url = reverse('scene-add-action', args=[scene.id])
        resp = self.client.post(url, {'device_id': 101, 'command': {'is_on': True}}, format='json')
        self.assertEqual(resp.status_code, 201)
        action_id = resp.data['id']
        del_url = reverse('scene-remove-action', args=[scene.id, action_id])
        del_resp = self.client.delete(del_url)
        self.assertEqual(del_resp.status_code, 204)

    def test_add_and_remove_trigger(self):
        scene = Scene.objects.create(name='模式B', owner=self.user)
        url = reverse('scene-add-trigger', args=[scene.id])
        resp = self.client.post(url, {'type': 'motion', 'config': {'sensor_id': 's1', 'state': 'detected'}}, format='json')
        self.assertEqual(resp.status_code, 201)
        trigger_id = resp.data['id']
        del_url = reverse('scene-remove-trigger', args=[scene.id, trigger_id])
        del_resp = self.client.delete(del_url)
        self.assertEqual(del_resp.status_code, 204)
